import requests
from tenacity import retry, stop_after_attempt, wait_exponential
from typing import Dict, List, Optional
import logging

class APIClient:
    """API 客户端，处理所有外部 API 调用"""
    
    def __init__(self, base_url: str = "http://180.184.65.98:38880/atomgit"):
        self.base_url = base_url
        self.session = requests.Session()
    
    @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
    def get_full_text(self, title: str) -> Optional[str]:
        """获取论文全文"""
        try:
            response = self.session.get(
                f"{self.base_url}/query_whole_text_by_title",
                params={"title": title},
                timeout=5
            )
            return response.text if response.status_code == 200 else None
        except Exception as e:
            logging.error(f"Failed to get full text: {e}")
            return None

    @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
    def get_papers_by_keyword(self, keyword: str) -> List[Dict]:
        """关键词查询论文"""
        try:
            response = self.session.get(
                f"{self.base_url}/query_by_keyword",
                params={"keyword": keyword},
                timeout=5
            )
            return response.json() if response.status_code == 200 else []
        except Exception as e:
            logging.error(f"Failed to get papers by keyword: {e}")
            return []
